import { defineStore } from 'pinia';
import { getAllUsers, createUser, updateUser, deleteUser } from '@/apis/user';

export const useUserManagementStore = defineStore('userManagement', {
  state: () => ({
    users: [],
    loading: false,
    error: null,
    isInitialized: false
  }),

  getters: {
    filteredUsers: (state) => (userType) => {
      if (!userType) return state.users;
      return state.users.filter(user => user.userType === parseInt(userType));
    }
  },

  actions: {
    async loadUsers(forceReload = false) {
      if (this.isInitialized && !forceReload && this.users.length > 0) {
        return;
      }

      this.loading = true;
      this.error = null;
      try {
        const response = await getAllUsers();
        if (response.code === 200) {
          this.users = response.data;
          this.isInitialized = true;
        } else {
          this.error = response.msg || '获取用户列表失败';
        }
      } catch (error) {
        this.error = error.message;
      } finally {
        this.loading = false;
      }
    },

    async addUser(userData) {
      this.loading = true;
      this.error = null;
      try {
        const response = await createUser(userData);
        if (response.code === 200) {
          await this.loadUsers(true);
          return { success: true, message: '添加成功' };
        }
        return { success: false, message: response.msg || '添加失败' };
      } catch (error) {
        return { success: false, message: error.message };
      } finally {
        this.loading = false;
      }
    },

    async updateUser(userId, userData) {
      this.loading = true;
      this.error = null;
      try {
        const response = await updateUser(userId, userData);
        if (response.code === 200) {
          await this.loadUsers(true);
          return { success: true, message: '更新成功' };
        }
        return { success: false, message: response.msg || '更新失败' };
      } catch (error) {
        return { success: false, message: error.message };
      } finally {
        this.loading = false;
      }
    },

    async deleteUser(userId) {
      this.loading = true;
      this.error = null;
      try {
        const response = await deleteUser(userId);
        if (response.code === 200) {
          await this.loadUsers(true);
          return { success: true, message: '删除成功' };
        }
        return { success: false, message: response.msg || '删除失败' };
      } catch (error) {
        return { success: false, message: error.message };
      } finally {
        this.loading = false;
      }
    },

    resetState() {
      this.users = [];
      this.loading = false;
      this.error = null;
      this.isInitialized = false;
    }
  },

  persist: true
}); 